package com.github.soiff.shadow.loader;

import com.github.jknack.handlebars.io.AbstractTemplateSource;
import com.github.soiff.shadow.common.ResourceFinder;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;

/**
 * Created by Soiff on 2016/05/23.
 *
 * @author : Soiff
 */
public class HandlebarsSource extends AbstractTemplateSource {
    @Override
    public String content() throws IOException {
        return this.content.toString();
    }

    @Override
    public String filename() {
        return null != this.file ? this.file.getFile() : null;
    }

    @Override
    public long lastModified() {
        return 0;
    }

    final private int bufsize = 1024;
    private URL file;
    private StringBuffer content = new StringBuffer(bufsize);
    public HandlebarsSource(Collection<ResourceFinder> finders, String path) throws IOException {
        for (ResourceFinder finder : finders) {
            this.file = finder.find(path);
            if (this.file == null) continue;

            final FileReader fr = new FileReader(this.file.getFile());
            final char[] cb = new char[bufsize];
            int len;
            while ((len = fr.read(cb, 0, cb.length)) >= 0)
                if (0 < len) this.content.append(cb, 0, len);
        }
    }
}
